<template>
  <div class="applicants-page">
    <n-card title="简历管理" class="cute-card">
      <template #header-extra>
        <n-button type="primary" @click="handleExport" size="small" round :loading="exporting">
          导出Excel
        </n-button>
      </template>
      
      <n-space vertical>
        <n-space class="search-bar">
          <n-input
            v-model:value="searchName"
            placeholder="搜索姓名"
            clearable
            @keyup.enter="handleSearch"
            style="width: 200px;"
          >
            <template #prefix>
              <n-icon>
                <SearchOutline />
              </n-icon>
            </template>
          </n-input>
          
          <n-select
            v-model:value="filterLink"
            placeholder="选择链接"
            clearable
            style="width: 200px;"
            :options="linkOptions"
            @update:value="handleSearch"
          />
          
          <n-button type="primary" ghost @click="handleSearch" size="small" round>
            搜索
          </n-button>
          <n-button @click="handleReset" size="small" round>
            重置
          </n-button>
        </n-space>
        
        <n-data-table
          :columns="columns"
          :data="applicants"
          :loading="loading"
          :pagination="pagination"
          :row-key="row => row.id"
          :bordered="false"
          striped
          class="resume-table"
        />
      </n-space>
      
      <!-- 详情模态框 -->
      <n-modal v-model:show="showDetailModal" preset="card" title="简历详情" style="width: 800px;">
        <div v-if="currentApplicant" class="applicant-detail">
          <div class="detail-header">
            <div class="detail-info">
              <h3>{{ currentApplicant.name }}</h3>
              <p v-if="currentApplicant.nickname">昵称：{{ currentApplicant.nickname }}</p>
              <p>手机号：{{ currentApplicant.phone }}</p>
              <p v-if="currentApplicant.wechat">微信号：{{ currentApplicant.wechat }}</p>
              <p>性别：{{ genderText(currentApplicant.gender) }}</p>
              <p>年龄：{{ currentApplicant.age || '未填写' }}</p>
              <p>体重：{{ currentApplicant.weight || '未填写' }} kg</p>
              <p>学历：{{ currentApplicant.education || '未填写' }}</p>
              <p>可否饮酒：{{ currentApplicant.can_drink === 'yes' ? '可以' : '不可以' }}</p>
              <p>能否配合直播：{{ currentApplicant.can_livestream === 'yes' ? '可以' : '不可以' }}</p>
              <p>是否能接受夜班：{{ currentApplicant.accept_night_shift === 'yes' ? '可以' : '不可以' }}</p>
              <p>期望工作时间：{{ currentApplicant.preferred_shift === 'day' ? '早班' : '晚班' }}</p>
              <p>游戏经验：
                {{ {
                  'none': '完全不了解',
                  'basic': '略有了解',
                  'familiar': '比较熟悉',
                  'expert': '非常熟悉'
                }[currentApplicant.game_experience] || '未填写' }}
              </p>
              <p>状态：
                <n-tag :type="{
                  'pending': 'warning',
                  'approved': 'success',
                  'rejected': 'error'
                }[currentApplicant.status] || 'default'" size="small" round>
                  {{ {
                    'pending': '待审核',
                    'approved': '已通过',
                    'rejected': '已拒绝'
                  }[currentApplicant.status] || '未知' }}
                </n-tag>
              </p>
              <p>提交时间：{{ formatDate(currentApplicant.created_at) }}</p>
            </div>
          </div>
          
          <n-divider />
          
          <div class="detail-section" v-if="currentApplicant.hobbies">
            <h4>兴趣爱好：</h4>
            <p>{{ currentApplicant.hobbies }}</p>
          </div>
          
          <div class="detail-section" v-if="currentApplicant.special_skills">
            <h4>才艺展示：</h4>
            <p>{{ currentApplicant.special_skills }}</p>
          </div>
          
          <div class="detail-section" v-if="currentApplicant.self_introduction">
            <h4>自我介绍：</h4>
            <p>{{ currentApplicant.self_introduction }}</p>
          </div>
          
          <div class="detail-section" v-if="currentApplicant.weekly_availability">
            <h4>每周空闲时间：</h4>
            <p>{{ currentApplicant.weekly_availability }}</p>
          </div>
          
          <div class="detail-section" v-if="currentApplicant.work_experience && currentApplicant.work_experience.length > 0">
            <h4>工作经历：</h4>
            <n-card v-for="(exp, index) in currentApplicant.work_experience" :key="index" class="work-exp-card">
              <p><strong>公司：</strong> {{ exp.company }}</p>
              <p><strong>职位：</strong> {{ exp.position }}</p>
              <p><strong>时间：</strong> {{ formatDate(exp.startDate, 'YYYY-MM-DD') }} 至 {{ formatDate(exp.endDate, 'YYYY-MM-DD') }}</p>
              <p v-if="exp.reasonForLeaving"><strong>离职原因：</strong> {{ exp.reasonForLeaving }}</p>
            </n-card>
          </div>
          
          <div class="detail-photos" v-if="currentApplicant.photos && currentApplicant.photos.length > 0">
            <h4>照片：</h4>
            <n-grid :cols="3" :x-gap="12" :y-gap="12">
              <n-grid-item v-for="(photo, index) in currentApplicant.photos" :key="index">
                <n-image
                  :src="photo"
                  object-fit="cover"
                  :width="200"
                  :height="200"
                  :preview-src="photo"
                  :preview-disabled="false"
                  :show-toolbar="true"
                  :show-toolbar-tooltip="true"
                />
              </n-grid-item>
            </n-grid>
          </div>
          
          <n-divider />
          
          <div class="detail-actions">
            <n-space>
              <n-button 
                type="success" 
                @click="updateStatus(currentApplicant.id, 'approved')" 
                :disabled="currentApplicant.status === 'approved'"
                size="medium"
                secondary
                style="min-width: 90px;"
              >
                <template #icon>
                  <n-icon><CheckmarkCircleOutline /></n-icon>
                </template>
                通过
              </n-button>
              <n-button 
                type="error" 
                @click="updateStatus(currentApplicant.id, 'rejected')" 
                :disabled="currentApplicant.status === 'rejected'"
                size="medium"
                secondary
                style="min-width: 90px;"
              >
                <template #icon>
                  <n-icon><CloseCircleOutline /></n-icon>
                </template>
                拒绝
              </n-button>
              <n-button
                type="primary"
                @click="printResumePDF"
                size="medium"
                secondary
                style="min-width: 90px;"
              >
                <template #icon>
                  <n-icon><PrintOutline /></n-icon>
                </template>
                打印简历
              </n-button>
            </n-space>
          </div>
        </div>
      </n-modal>
      
      <!-- 简历打印预览模态框 -->
      <n-modal v-model:show="showPrintModal" preset="card" title="简历打印预览" style="width: 950px; max-width: 95vw;">
        <div class="print-preview-container">
          <resume-print-template v-if="currentApplicant" :resume="currentApplicant" ref="printTemplateRef" />
        </div>
        <template #footer>
          <n-space justify="end">
            <n-button @click="showPrintModal = false">关闭</n-button>
            <n-button type="primary" @click="downloadPDF">
              <template #icon>
                <n-icon><DownloadOutline /></n-icon>
              </template>
              下载PDF
            </n-button>
            <n-button type="info" @click="printPDF">
              <template #icon>
                <n-icon><PrintOutline /></n-icon>
              </template>
              打印
            </n-button>
          </n-space>
        </template>
      </n-modal>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, h, onMounted, computed } from 'vue'
import { useMessage, useDialog, NButton } from 'naive-ui'
import { 
  SearchOutline, 
  CheckmarkCircleOutline, 
  CloseCircleOutline,
  EyeOutline,
  TrashOutline,
  PrintOutline,
  DownloadOutline
} from '@vicons/ionicons5'
import { formatDate } from '../../utils/date'
import { saveExcelFile } from '../../utils/exportExcel'
import { generateResumePDF, printResume } from '../../utils/pdfUtils'
import adminApi from '../../api/admin'
import ResumePrintTemplate from '../../components/ResumePrintTemplate.vue'

const message = useMessage()
const dialog = useDialog()
const loading = ref(false)
const exporting = ref(false)
const applicants = ref([])
const links = ref([])
const showDetailModal = ref(false)
const showPrintModal = ref(false)
const currentApplicant = ref(null)
const searchName = ref('')
const filterLink = ref(null)
const printTemplateRef = ref(null)

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30, 50],
  onChange: (page) => {
    pagination.page = page
    getApplicants()
  },
  onUpdatePageSize: (pageSize) => {
    pagination.pageSize = pageSize
    pagination.page = 1
    getApplicants()
  }
})

// 链接选项
const linkOptions = computed(() => {
  return links.value.map(link => ({
    label: `链接 #${link.id} (${formatDate(link.createdAt, 'YYYY-MM-DD')})`,
    value: link.id
  }))
})

// 性别文本
const genderText = (gender) => {
  const map = {
    male: '男',
    female: '女',
    other: '其他'
  }
  return map[gender] || '未知'
}

// 表格列定义
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 80
  },
  {
    title: '姓名',
    key: 'name'
  },
  {
    title: '手机号',
    key: 'phone'
  },
  {
    title: '性别',
    key: 'gender',
    render(row) {
      return genderText(row.gender)
    }
  },
  {
    title: '年龄',
    key: 'age',
    render(row) {
      return row.age || '-'
    }
  },
  {
    title: '体重(kg)',
    key: 'weight',
    render(row) {
      return row.weight || '-'
    }
  },
  {
    title: '学历',
    key: 'education',
    render(row) {
      return row.education || '-'
    }
  },
  {
    title: '饮酒',
    key: 'can_drink',
    render(row) {
      return row.can_drink === 'yes' ? '可以' : '不可以'
    }
  },
  {
    title: '直播',
    key: 'can_livestream',
    render(row) {
      return row.can_livestream === 'yes' ? '可以' : '不可以'
    }
  },
  {
    title: '接受夜班',
    key: 'accept_night_shift',
    render(row) {
      return row.accept_night_shift === 'yes' ? '可以' : '不可以'
    }
  },
  {
    title: '工作时间',
    key: 'preferred_shift',
    render(row) {
      const map = {
        day: '早班',
        night: '晚班'
      }
      return map[row.preferred_shift] || '-'
    }
  },
  {
    title: '游戏经验',
    key: 'game_experience',
    render(row) {
      const map = {
        none: '完全不了解',
        basic: '略有了解',
        familiar: '比较熟悉',
        expert: '非常熟悉'
      }
      return map[row.game_experience] || '-'
    }
  },
  {
    title: '状态',
    key: 'status',
    render(row) {
      const statusMap = {
        pending: { text: '待审核', type: 'warning', color: '#f0a020', bgColor: '#fff8e6' },
        approved: { text: '已通过', type: 'success', color: '#18a058', bgColor: '#e8f5e9' },
        rejected: { text: '已拒绝', type: 'error', color: '#d03050', bgColor: '#ffebee' }
      }
      const status = statusMap[row.status] || { text: '未知', type: 'default', color: '#909399', bgColor: '#f4f4f5' }
      
      return h(
        'div',
        {
          class: 'status-tag',
          style: `
            background-color: ${status.bgColor};
            color: ${status.color};
            border: 1px solid ${status.color};
            padding: 2px 8px;
            border-radius: 12px;
            display: inline-block;
            font-size: 12px;
            text-align: center;
            min-width: 64px;
          `
        },
        status.text
      )
    }
  },
  {
    title: '提交时间',
    key: 'created_at',
    render(row) {
      return formatDate(row.created_at)
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    // h(NButton, {
    //       size: 'small',
    //       type: 'primary',
    //       text: true,
    //       disabled: isExpired(row.expiresAt),
    //       onClick: () => showQRCode(row),
    //       style: {
    //         padding: '4px 12px'
    //       }
    //     }, { default: () => '查看二维码' }),
    render(row) {
      return h(
        'div',
        {
          class: 'table-actions'
        },
        [
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              secondary: true,
              onClick: () => showDetail(row),
              style: 'margin-right: 8px; min-width: 80px;'
            },
            { 
              default: () => '查看详情',
            }
          ),
          h(
            NButton,
            {
              size: 'small',
              type: 'error',
              secondary: true,
              onClick: () => confirmDelete(row),
              style: 'min-width: 60px;'
            },
            { 
              default: () => '删除',
            }
          )
        ]
      )
    }
  }
]

// 获取所有简历
const getApplicants = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      name: searchName.value,
      linkId: filterLink.value
    }
    
    const res = await adminApi.getApplicants(params)
    
    // 检查返回的数据结构
    console.log('获取简历返回数据:', res)
    
    if (res.success && res.data) {
      // 正确处理嵌套的数据结构
      applicants.value = res.data.list || []
      pagination.itemCount = res.data.total || 0
    } else {
      applicants.value = []
      pagination.itemCount = 0
      message.error('返回数据格式不正确')
    }
  } catch (error) {
    console.error('获取简历失败:', error)
    message.error('获取简历列表失败')
    applicants.value = []
    pagination.itemCount = 0
  } finally {
    loading.value = false
  }
}

// 获取所有链接
const getLinks = async () => {
  try {
    const res = await adminApi.getLinks()
    links.value = res.data || []
  } catch (error) {
    console.error('获取链接失败:', error)
    message.error('获取链接列表失败')
  }
}

// 显示详情
const showDetail = async (row) => {
  try {
    loading.value = true
    // 先获取完整的简历数据
    const res = await adminApi.getApplicantDetail(row.id)
    
    if (res.success && res.data) {
      currentApplicant.value = res.data
      showDetailModal.value = true
    } else {
      message.error('获取简历详情失败')
    }
  } catch (error) {
    console.error('获取简历详情失败:', error)
    message.error('获取简历详情失败')
  } finally {
    loading.value = false
  }
}

// 确认删除
const confirmDelete = (row) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除此链接吗？删除后无法恢复。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => handleDelete(row.id)
  })
}

// 处理删除
const handleDelete = async (id) => {
  loading.value = true
  try {
    const res = await adminApi.deleteApplicant(id)
    
    if (res.success) {
      message.success('删除成功')
      // 重新加载列表数据
      await getApplicants()
    } else {
      message.error(res.message || '删除失败')
      loading.value = false
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
    loading.value = false
  }
  // 不需要在finally中设置loading.value = false，因为getApplicants会处理
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  getApplicants()
}

// 处理重置
const handleReset = () => {
  searchName.value = ''
  filterLink.value = null
  pagination.page = 1
  getApplicants()
}

// 处理导出
const handleExport = async () => {
  exporting.value = true
  try {
    const params = {
      linkId: filterLink.value,
      status: null // 可以根据需要添加状态过滤
    }
    
    const res = await adminApi.exportApplicants(params)
    
    // 调试输出，查看返回的数据结构
    console.log('导出数据:', res)
    
    if (res.success && res.data) {
      // 检查数据中是否包含职位和部门字段
      if (res.data.length > 0) {
        console.log('第一条数据示例:', res.data[0])
      }
      
      await saveExcelFile(res, '简历列表')
      message.success('导出成功')
    } else {
      message.error(res.message || '导出失败，没有数据')
    }
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败，请检查网络连接')
  } finally {
    exporting.value = false
  }
}

// 处理状态更新
const updateStatus = async (id, newStatus) => {
  const loadingBar = window.$loadingBar
  if (loadingBar) loadingBar.start()
  
  try {
    // 调用API更新状态
    const res = await adminApi.updateApplicantStatus(id, newStatus)
    
    if (res.success) {
      message.success(`状态已更新为 ${newStatus === 'approved' ? '通过' : '拒绝'}`)
      
      // 更新当前详情数据的状态
      if (currentApplicant.value && currentApplicant.value.id === id) {
        currentApplicant.value.status = newStatus
      }
      
      // 重新加载列表数据
      await getApplicants()
    } else {
      message.error(res.message || '更新状态失败')
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    message.error('更新状态失败，请重试')
  } finally {
    if (loadingBar) loadingBar.finish()
  }
}

// 打印简历
const printResumePDF = () => {
  showPrintModal.value = true
}

// 下载PDF
const downloadPDF = async () => {
  try {
    if (!printTemplateRef.value) {
      message.error('模板未加载完成');
      return;
    }
    
    const element = printTemplateRef.value.$el;
    await generateResumePDF(element, `${currentApplicant.value.name}_简历`);
    message.success('PDF已生成');
  } catch (error) {
    console.error('生成PDF失败:', error);
    message.error('生成PDF失败');
  }
}

// 打印PDF
const printPDF = async () => {
  try {
    if (!printTemplateRef.value) {
      message.error('模板未加载完成');
      return;
    }
    
    const element = printTemplateRef.value.$el;
    await printResume(element);
    message.success('已发送到打印队列');
  } catch (error) {
    console.error('打印失败:', error);
    message.error('打印失败');
  }
}

onMounted(() => {
  getApplicants()
  getLinks()
})
</script>

<style scoped>
.applicants-page {
  padding: 20px;
}

.search-bar {
  margin-bottom: 16px;
}

.applicant-detail {
  padding: 16px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.detail-info {
  flex: 1;
}

.detail-info h3 {
  margin-top: 0;
  margin-bottom: 12px;
  color: var(--primary-color);
  font-weight: 600;
}

.detail-info p {
  margin: 8px 0;
  color: #333;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.detail-photos {
  margin-top: 20px;
}

.work-exp-card {
  margin-bottom: 12px;
}

.work-exp-card p {
  margin: 4px 0;
}

.detail-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  text-align: center;
  min-width: 64px;
}

.table-actions {
  display: flex;
  justify-content: center;
}

.resume-table {
  font-size: 14px;
}

.resume-table :deep(th) {
  font-weight: 600;
}

.print-preview-container {
  padding: 16px;
  max-height: 80vh;
  overflow-y: auto;
  display: flex;
  justify-content: center;
}

/* 打印模式下的样式 */
@media print {
  .resume-print-template {
    margin: 0;
    padding: 0;
    box-shadow: none;
  }
}
</style> 